# -*- coding:utf-8 -*-

from urllib import parse
import requests, re

"""
微信download url，转成视频地址
download_url 组成中获取video_id参数，
拼凑参数，如该链接 https://aweme.snssdk.com/aweme/v1/playwm/?video_id=VIDEOID参数&line=0，
requests.url 获取重定向的连接
重定向连接即为下载连接
"""


class DouyinTransform(object):

    def get_real_url(self, url=''):
        '''
        获取真实的视频播放地址
        :param url: json播放视频地址
        :return: 真实视频播放地址
        '''
        parse_result = parse.urlparse(url)
        parse_dict = parse.parse_qs(parse_result.query)
        if 'video_id' not in parse_dict.keys():
            return ''
        video_id = parse_dict['video_id'][0]

        url_template = 'http://aweme.snssdk.com/aweme/v1/playwm/?video_id=%s&line=0' % video_id
        print(url_template)
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            'Host': 'aweme.snssdk.com',
            "Content-Type": "text/html; charset=UTF-8",
            "Connection": "keep-alive",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,ja;q=0.6",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
        }
        try:
            redirect_url = requests.get(url_template, headers=headers, timeout=2)
            end_url = redirect_url.url
        except Exception:
            end_url = ''

        # 检查最终的url域名是否正确
        # end_url = 'http://v3-dy-z.ixigua.com/ba6e513be31d4f34fa867d177c3e2eb9/5b7f6f13/video/m/2206c64ec7f631448acbb7911da94ed3ddf115647920000c3228bd246ad/'
        pattern = re.search(r'\.ixigua\.com', end_url)
        if pattern is None:
            data_url = ''
        else:
            data_url = end_url
        return data_url



if __name__ == '__main__':
    url = 'https://aweme.snssdk.com/aweme/v1/play/?video_id=0fa1c82beb654bf3b3eeb1b93454c1e1&line=0&ratio=720p&media_type=4&vr_type=0&test_cdn=None&improve_bitrate=0'
    # url = 'https://aweme.snssdk.com/aweme/v1/play/'
    #
    # print(parse_dict)
    douyin_tool = DouyinTransform()
    data = douyin_tool.get_real_url(url)
    print(data)
